package com.cdxy.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

public class VerifyCode {
    private int w = 120;
    private int h = 40;
    private String text;
    private Random random = new Random();
    private Color bgColor = new Color(255, 255, 255);
    private String[] fontNames = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};//候选字体
    private String codes = "0123456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";//候选字母

    //随机字体
    private Color randomColor() {
        int red = random.nextInt(150);
        int green = random.nextInt(150);
        int blue = random.nextInt(150);
        return new Color(red, green, blue);
    }

    //随机颜色
    private Font randFont() {
        int index = random.nextInt(fontNames.length);
        String fontName = fontNames[index];//随机字体名称
        int style = random.nextInt(4);//随机样式, 0 无样式， 1 粗体 ， 2 斜体， 3 粗斜体
        int size = random.nextInt(4) + 24;//随机字号, 24 - 28
        return new Font(fontName, style, size);
    }

    //三根干扰线
    private void drawLine(BufferedImage image) {
        int num = 3;
        Graphics2D g2 = (Graphics2D) image.getGraphics();//获取绘制环境
        for (int i = 0; i < num; i++) {
            int x1 = random.nextInt(w);
            int y1 = random.nextInt(h);
            int x2 = random.nextInt(w);
            int y2 = random.nextInt(h);
            g2.setStroke(new BasicStroke(1.5F));
            g2.setColor(Color.blue);
            g2.drawLine(x1, y1, x2, y2);
        }
    }

    //生成一个字符
    private char randomChar() {
        int index = random.nextInt(codes.length());
        return codes.charAt(index);
    }

    //创建 BufferedImage
    private BufferedImage createImage() {
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        g2.setColor(this.bgColor);
        g2.fillRect(0, 0, w, h);
        return image;
    }

    //获取验证码
    public BufferedImage getImage() {
        BufferedImage image = createImage();//创建图片缓冲区
        Graphics2D g2 = (Graphics2D) image.getGraphics();//得到绘制环境
        StringBuilder sb = new StringBuilder();//装填生成验证码文本
        for (int i = 0; i < 4; i++) {
            String s = randomChar() + "";
            sb.append(s);//随机生成一个字母并放入 sb 中
            float x = i * 1.0F * w / 4;//当前字符 x 轴
            g2.setFont(randFont());
            g2.setColor(randomColor());
            g2.drawString(s, x, h - 5);//绘图
        }
        this.text = sb.toString();
        drawLine(image);//添加干扰线
        return image;
    }

    public String getText() {
        return text;
    }

    public void output(BufferedImage img, OutputStream out) throws IOException {
        ImageIO.write(img, "JPEG", out);
    }
}
